package com.topnav.mc.admin.security.filter;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.topnav.mc.exception.ExceptionMsg;
import com.topnav.mc.uitls.ErrorResultUtil;
import com.topnav.mc.uitls.VerifyCodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 验证码拦截器
 * @Author: kenny
 * @Date: 2024/1/5 17:17
 */
@Component
@Slf4j
public class VerifyCodeFilter extends OncePerRequestFilter {
    @Resource
    private VerifyCodeUtil verifyCodeUtil;
    private static final String CAPTCHA_SESSION_KEY = "captcha";
    private static final String CAPTCHA_PARAM_NAME = "captcha";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
/*        log.info(">>>>>>>>> VerifyCodeFilter: method={}",(request.getMethod()));
        log.info(">>>>>>>>> VerifyCodeFilter: Uri={}",(request.getRequestURI()));
        log.info(">>>>>>>>> VerifyCodeFilter: username={}",(request.getParameter("username")));
        log.info(">>>>>>>>> VerifyCodeFilter: password={}",(request.getParameter("password")));
        log.info(">>>>>>>>> VerifyCodeFilter: sessionId={}",(request.getParameter("sessionId")));
        log.info(">>>>>>>>> VerifyCodeFilter: verifyCode={}",(request.getParameter("verifyCode")));
        log.info(">>>>>>>>> VerifyCodeFilter: dev={}",(request.getParameter("dev")));*/
        String sessionId = request.getParameter("sessionId");
        String verifyCode = request.getParameter("verifyCode");
/*        log.debug("url: {}",request.getRequestURI());
        log.debug("sessionId: {}",request.getParameter("sessionId"));
        log.debug("verifyCode: {}",request.getParameter("verifyCode"));
        log.debug("dev: {}",request.getParameter("dev"));*/


        if (StringUtils.isEmpty(request.getParameter("dev")) && "/login".equalsIgnoreCase(request.getRequestURI())){
            if (StringUtils.isEmpty(request.getParameter("verifyCode"))){
                this.sendError(response,JSON.toJSONString(ErrorResultUtil.result(ExceptionMsg.ERROR_AUTHENTICATION_VERIFY_EMPTY)));
/*                response.sendError(ExceptionMsg.ERROR_AUTHENTICATION_VERIFY_EMPTY.getCode(),
                        ExceptionMsg.ERROR_AUTHENTICATION_VERIFY_EMPTY.getDesc()
                );*/
                return;
                //throw ExceptionUtil.commonException(ExceptionMsg.ERROR_AUTHENTICATION_VERIFY_EMPTY) ;
            }
            if (StringUtils.isEmpty(sessionId)){
/*                response.sendError(ExceptionMsg.ERROR_AUTHENTICATION_SESSIONID_EMPTY.getCode(),
                        ExceptionMsg.ERROR_AUTHENTICATION_SESSIONID_EMPTY.getDesc()
                );*/
                this.sendError(response,JSON.toJSONString(ErrorResultUtil.result(ExceptionMsg.ERROR_AUTHENTICATION_SESSIONID_EMPTY)));
                return;
                //throw ExceptionUtil.commonException(ExceptionMsg.ERROR_AUTHENTICATION_SESSIONID_EMPTY) ;
            }

            JSONObject json = verifyCodeUtil.get(sessionId);
            if (StringUtils.isEmpty(json)){
/*                response.sendError(ExceptionMsg.ERROR_AUTHENTICATION_VERIFYCODE_EXPIRE.getCode(),
                        ExceptionMsg.ERROR_AUTHENTICATION_VERIFYCODE_EXPIRE.getDesc()
                );*/
                this.sendError(response,JSON.toJSONString(ErrorResultUtil.result(ExceptionMsg.ERROR_AUTHENTICATION_VERIFYCODE_EXPIRE)));
                return;
                //throw ExceptionUtil.commonException(ExceptionMsg.ERROR_AUTHENTICATION_VERIFYCODE_EXPIRE) ;
            }

            if (!verifyCode.equals(json.getString("success"))){
/*                response.sendError(ExceptionMsg.ERROR_AUTHENTICATION_VERIFYCODE_FAILED.getCode(),
                        ExceptionMsg.ERROR_AUTHENTICATION_VERIFYCODE_FAILED.getDesc()
                );*/
                this.sendError(response,JSON.toJSONString(ErrorResultUtil.result(ExceptionMsg.ERROR_AUTHENTICATION_VERIFYCODE_FAILED)));
                return;
                //throw ExceptionUtil.commonException(ExceptionMsg.ERROR_AUTHENTICATION_VERIFYCODE_FAILED) ;
            }
        }
/*
        if (request.getMethod().equalsIgnoreCase("POST")) { //只对POST请求进行验证码验证
            HttpSession session = request.getSession(false);
            if (session != null) {
                //拿到session中存放的 captcha 属性
                String captcha = (String) session.getAttribute(CAPTCHA_SESSION_KEY);
                if (captcha == null) {
                    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "验证码已过期，请重新获取。");
                    return;
                }
                //获取输入的验证码信息
                String inputCaptcha = request.getParameter(CAPTCHA_PARAM_NAME);
                if (inputCaptcha == null || !captcha.equals(inputCaptcha.trim())) {
                    response.sendError(HttpServletResponse.SC_BAD_REQUEST, "验证码错误，请重新输入。");
                    return;
                }
            } else {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "无法验证验证码，因为HTTP会话不存在。");
                return;
            }
        }*/
        filterChain.doFilter(request, response);
    }

    private void sendError(HttpServletResponse response,String json) throws IOException, ServletException{
        // 允许跨域
        response.setHeader("Access-Control-Allow-Origin", "*");
        // 允许自定义请求头token(允许head跨域)
        response.setHeader("Access-Control-Allow-Headers", "token, Accept, Origin, X-Requested-With, Content-Type, Last-Modified");

        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(json);
    }
}
